package com.acdc.utils;
/**
 * OTA文件切包工具类
 */
import java.io.*;
import java.util.ArrayList;
import java.util.List;
 
public class FileBinarySplitter {
    
    private static final int CHUNK_SIZE = 128;
    
    public static class ChunkWithChecksum {
        private byte[] data;
        private int checksum;
        
        public ChunkWithChecksum(byte[] data, int checksum) {
            this.data = data;
            this.checksum = checksum;
        }
        
        public byte[] getData() {
            return data;
        }
        
        public int getChecksum() {
            return checksum;
        }
        
        @Override
        public String toString() {
            return "ChunkWithChecksum{data.length=" + data.length + ", checksum=" + checksum + "}";
        }

        // 将checksum转换为十六进制字符串
        public String getChecksumHex() {
            return Integer.toHexString(checksum).toUpperCase();
        }
    }
    
    /**
     * 将文件按128字节分组，并计算每组的校验和
     * @param filePath 文件路径
     * @return 包含数据和校验和的分组列表
     * @throws IOException 文件读取异常
     */
    public static List<ChunkWithChecksum> splitFileWithChecksum(String filePath) throws IOException {
        List<ChunkWithChecksum> chunks = new ArrayList<>();
        
        try (FileInputStream fis = new FileInputStream(filePath)) {
            byte[] buffer = new byte[CHUNK_SIZE];
            int bytesRead;
            
            while ((bytesRead = fis.read(buffer)) != -1) {
                // 如果读取的字节数少于128，创建一个新的数组只包含实际读取的数据
                byte[] chunkData;
                if (bytesRead < CHUNK_SIZE) {
                    chunkData = new byte[bytesRead];
                    System.arraycopy(buffer, 0, chunkData, 0, bytesRead);
                } else {
                    chunkData = buffer.clone();
                }
                
                // 计算校验和
                int checksum = calculateChecksum(chunkData);
                
                // 添加到结果列表
                chunks.add(new ChunkWithChecksum(chunkData, checksum));
            }
        }
        
        return chunks;
    }
    
    /**
     * 计算字节数组的校验和（简单累加）
     * @param data 字节数组
     * @return 校验和
     */
    private static int calculateChecksum(byte[] data) {
        int sum = 0;
        for (byte b : data) {
            sum += (b & 0xFF); // 将byte转换为无符号整数进行累加
        }
        return sum;
    }
    
    /**
     * 测试方法：验证十六进制字符串的校验和计算
     * @param hexString 十六进制字符串（可以包含空格）
     * @return 校验和
     */
    public static int calculateHexStringChecksum(String hexString) {
        // 移除空格并转换为字节数组
        String cleanHex = hexString.replaceAll("\\s", "");
        byte[] data = new byte[cleanHex.length() / 2];
        
        for (int i = 0; i < data.length; i++) {
            int index = i * 2;
            data[i] = (byte) Integer.parseInt(cleanHex.substring(index, index + 2), 16);
        }
        
        return calculateChecksum(data);
    }
}
 
